load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
load("@rules_oci//oci:defs.bzl", "oci_image")
load("@rules_pkg//:pkg.bzl", "pkg_tar")
load("//bazel/go:platform.bzl", "platform_binary")
load("//bazel/patchelf:patchelf.bzl", "patchelf")

go_library(
    name = "qemu-metadata-api_lib",
    srcs = [
        "main.go",
        "main_cross.go",
    ],
    importpath = "github.com/edgelesssys/constellation/v2/hack/qemu-metadata-api",
    visibility = ["//visibility:private"],
    deps = [
        "//hack/qemu-metadata-api/dhcp/dnsmasq",
        "//hack/qemu-metadata-api/dhcp/virtwrapper",
        "//hack/qemu-metadata-api/server",
        "//internal/logger",
        "@org_libvirt_go_libvirt//:libvirt",
    ],
)

go_binary(
    name = "qemu-metadata-api",
    embed = [":qemu-metadata-api_lib"],
    visibility = ["//visibility:public"],
)

platform_binary(
    name = "qemu_metadata_api_linux_amd64",
    platform = "//bazel/platforms:constellation_os",
    target_file = ":qemu-metadata-api",
    visibility = ["//visibility:public"],
)

patchelf(
    name = "qemu_metadata_api_patched",
    src = ":qemu_metadata_api_linux_amd64",
    out = "qemu_metadata_api_with_nix_rpath",
    interpreter = "@libvirt_x86_64-linux//:dynamic-linker",
    rpath = "@libvirt_x86_64-linux//:rpath",
)

pkg_tar(
    name = "layer",
    srcs = [
        ":qemu_metadata_api_patched",
    ],
    mode = "0755",
    remap_paths = {"/qemu_metadata_api_with_nix_rpath": "/server"},
)

oci_image(
    name = "qemumetadata",
    architecture = "amd64",
    entrypoint = ["/server"],
    os = "linux",
    tars = [
        "@libvirt_x86_64-linux//:closure.tar",
        ":layer",
    ],
    visibility = ["//visibility:public"],
)
